﻿using System.Linq;
using CardPlay.Model.CardModel;
using CardPlay.Model.GameModel;
using CardPlay.Model.GameModel.Presentation;
using CardPlay.Model.Layout;
using CardPlay.Model.Primitives;

namespace CardPlay.DemoPack.Games.PairingVariants
{
    [Game("424DB374-04A9-48E8-BC2A-95DBAD9033B0", LevelOfDifficulty.Easy, LevelOfSkill.ChanceOnly, DurationOfPlay.LessThan5Minutes, Family = FamilyName)]
    public class Doublets : PairingStyleGame
    {
        public Doublets()
        {
            NamesOfAdditionalPiles.Add(Reserve);
            TotalTableaus = 12;
        }

        protected override bool IsOver
        {
            get
            {
                var tableau = this.NonEmptyPilesNamed(AnyTableau);
                return this[Reserve].IsEmpty && tableau.All(pile => pile.TopCard.IsFaceUp) && !SetHasPair(tableau);
            }
        }

        public override ILayoutSite CreatePresentation(IPresentationContext presentation)
        {
            var root = presentation.CreateColumnLayout();
            root.Add(presentation.CreatePileVisual(Reserve, new VisualTraits { Arrangement = CardArrangement.StackLeftToRight, ContentFit = ContentFit.FitHeight }));

            var row1 = presentation.CreateRowLayout();
            root.Add(row1);

            var tableauStyle = StandardStyles.Reserve;
            tableauStyle.MinimumSize = new Size(presentation.Metrics.CardSize.Width + presentation.Metrics.MinSpacingAcross, presentation.Metrics.CardSize.Height);

            row1.MaximumSize = new Size(0, presentation.Metrics.CardSize.Height * 2);
            presentation.AddPiles(row1, NamesOfTableaus.Take(6), tableauStyle);

            var row2 = presentation.CreateRowLayout();
            root.Add(row2);

            presentation.AddPiles(row2, NamesOfTableaus.Skip(6), tableauStyle);
            return root;
        }

        protected override void PrepareDealScript(DealScript script)
        {
            script.Deal("4 down").To(Reserve);
            script.DealToEach(NamesOfTableaus, "3 down;up");
        }

        protected override void OnTransactionEnding()
        {
            this.FlipFaceDownTopCardsInPilesMatching(AnyTableau);
            this.FillEmptyPilesMatching(AnyTableau, this[Reserve]);
        }
    }
}